/**
 * @description vue.config.js全局配置
 */
// 组件自动加载
const AutoImport = require('unplugin-auto-import/webpack')
const Components = require('unplugin-vue-components/webpack')
const { AntDesignVueResolver } = require('unplugin-vue-components/resolvers')
const path = require('path')

const resolve = dir => {
  return path.join(__dirname, dir)
}
const isProd = process.env.NODE_ENV === 'production'
const { publicPath, assetsDir, outputDir, devPort, modifyVars } = require('./src/config')
// 需要配置的 CDN 链接
const cdn = { css: [], js: [] }
// 打包压缩
const CompressionWebpackPlugin = require('compression-webpack-plugin')
// 根据环境配置标题
module.exports = {
  publicPath, // 部署应用包时的基本 URL
  outputDir,
  assetsDir,
  productionSourceMap: false, // 去除Map文件。减少包大小，也可以加密源码
  devServer: {
    hot: true,
    port: devPort,
    open: true,
    proxy: {
      '/pro': {
        target: 'http://192.168.101.125:7082', // 连接后端时接口地址
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          '^/pro': ''
        }
      }
    }
  },
  configureWebpack() {
    return {
      resolve: {
        // 支持js、ts混用
        extensions: ['.ts', '.tsx', '.js', '.json'],
        // 配置alias简称
        alias: {
          '@': resolve('src'),
          '*': resolve('')
        }
      },
      module: {
        rules: [
          {
            test: /\.tsx?$/,
            loader: 'ts-loader',
            exclude: /node_modules/,
            options: {
              appendTsSuffixTo: [/\.vue$/]
            }
          }
        ]
      },
      plugins: [
        AutoImport({
          include: [
            /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
            /\.vue$/,
            /\.vue\?vue/, // .vue
            /\.md$/ // .md
          ],
          imports: ['vue', 'pinia', 'vue-router'],
          eslintrc: {
            enabled: false,
            filepath: './.eslintrc-auto-import.json',
            globalsPropValue: true
          },
          dts: './src/auto-import.d.ts',
          resolvers: [AntDesignVueResolver()]
        }),
        Components({
          resolvers: [
            AntDesignVueResolver({
              resolveIcons: true, // 自动引入 ant-design/icons-vue中的图标，需要安装@ant-design/icons-vue
              importStyle: false // 指是否需要自动随引入加载对应的组件样式，设置为 false，因为某些二级组件（比如 DateRangePicker）没办法准确地识别正确路径，他的搜寻路径都是按一级组件来写的
            })
          ],
          dts: true,
          dirs: ['src/components'] // 配置需要默认导入的自定义组件文件夹，该文件夹下的所有组件都会自动 import
        })
      ]
    }
  },
  css: {
    // 全局样式
    loaderOptions: {
      less: {
        lessOptions: {
          javascriptEnabled: true,
          modifyVars
        }
      }
    }
  },
  chainWebpack(config) {
    config.plugins.delete('prefetch')
    config.plugins.delete('preload')
    // 设置svg
    config.module.rule('svg').exclude.add(resolve('src/assets/icons')).end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()
    // 设置开发环境sourceMap
    config.when(!isProd, config => config.devtool('cheap-source-map'))
    // 生产环境
    config.when(isProd, config => {
      config.optimization.splitChunks({
        chunks: 'all',
        cacheGroups: {
          libs: {
            name: 'chunk-libs',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial'
          },
          commons: {
            name: 'chunk-commons',
            test: /[\\/]src[\\/]js[\\/]/,
            minChunks: 2, //  minimum common number
            priority: 5,
            reuseExistingChunk: true
          }
        }
      })

      config.plugin('html').tap(args => {
        args[0].cdn = cdn
        return args
      })

      config.optimization.runtimeChunk('single')

      // 去除生产环境debugger 和console
      // config.optimization.minimizer('terser').tap(args => {
      //   args[0].terserOptions.compress.warnings = false
      //   args[0].terserOptions.compress.drop_console = true
      //   args[0].terserOptions.compress.drop_debugger = true
      //   args[0].terserOptions.compress.pure_funcs = ['console.*']
      //   return args
      // })
      // g-zip开启
      config.plugin('CompressionWebpackPlugin').use(CompressionWebpackPlugin, [
        {
          filename: '[path].gz[query]',
          algorithm: 'gzip',
          test: /\.js$|\.css/, // 匹配文件名
          threshold: 10240, // 对超过10k的数据压缩
          minRatio: 0.8
        }
      ])
      // 打包大小分析
      if (process.env.npm_config_report) {
        config.plugin('webpack-bundle-analyzer').use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
      }
    })
  }
}
